<template>
  <div class="login-container">
    <div class="login-form">
      <div class="login-header">
        <img src="@/assets/imgs/logo.png" alt="Logo" class="login-logo" />
        <h2>{{ params.AdminName }}</h2>
        <p>欢迎登录管理系统</p>
      </div>

      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form-content"
        @keyup.enter="handleLogin">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名" size="large">
            <template #prefix>
              <el-icon>
                <User />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" size="large" show-password>
            <template #prefix>
              <el-icon>
                <Lock />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="captcha">
          <el-input v-model="loginForm.captcha" placeholder="请输入验证码" size="large">
            <template #prefix>
              <el-icon>
                <Lock />
              </el-icon>
            </template>
          </el-input>
          <img :src="captchaJpgUrl" alt="验证码" class="captcha-image" @click="loadCaptchaJpg" />
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
        </el-form-item>

      </el-form>

      <div class="form-footer">
        <el-button type="primary" @click="handleLogin" :loading="loading" size="large" class="login-btn">
          登录
        </el-button>

        <div class="form-links">
          <el-link type="primary" @click="goToRegister">还没有账号？立即注册</el-link>
          <el-link type="info" @click="handleForgotPassword">忘记密码？</el-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { useUser } from '@/store/user'
import md5 from 'js-md5'
import { v4 as uuidv4 } from 'uuid'

const router = useRouter()
const loginFormRef = ref<FormInstance>()

const loading = ref(false)
const captchaJpgUrl = ref('')

const { params, login } = useUser()

const loginForm = reactive({
  username: '',
  password: '',
  captcha: '',
  uuid: '',
  remember: true
})

const loginRules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在3-20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6-20个字符之间', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
})

const handleLogin = async () => {
  if (!loginFormRef.value) return

  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      loginForm.password = md5.md5(loginForm.password)
      //保存记住账号
      if (loginForm.remember) {
        localStorage.setItem('rememberedUsername', loginForm.username)
      }
      //用户登录
      const res = await login(loginForm)
      loading.value = false
      if (res.code == 200) {
        ElMessage.success('登录成功')
        router.push('/')
      } else {
        ElMessage.error(res.message || '登录失败')
      }
    }
  })
}

const loadCaptchaJpg = async () => {
  captchaJpgUrl.value = location.origin + "/api/captcha/jpg?uuid=" + loginForm.uuid + "&t=" + new Date().getTime()
}

const goToRegister = () => {
  router.push('/register')
}

const handleForgotPassword = () => {
  ElMessage.info('请联系管理员重置密码')
}

onMounted(() => {
  //获取记住账号
  if (localStorage.getItem('rememberedUsername')) {
    loginForm.username = localStorage.getItem('rememberedUsername') || ''
    loginForm.remember = true
  }
  //生成uuid
  if (localStorage.getItem('uuid')) {
    loginForm.uuid = localStorage.getItem('uuid') || ''
  } else {
    loginForm.uuid = uuidv4()
    localStorage.setItem('uuid', loginForm.uuid)
  }
  //加载验证码
  loadCaptchaJpg()
})
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-form {
  width: 100%;
  max-width: 400px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 10px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-logo {
  width: 80px;
  height: 80px;
}

.login-header h2 {
  margin: 10px 0;
  color: #333;
}

.login-header p {
  color: #666;
  margin: 0;
}

.login-form-content {
  margin-bottom: 20px;
}

.login-btn {
  width: 100%;
}

.form-footer {
  text-align: center;
}

.form-links {
  margin-top: 15px;
}

.form-links .el-link {
  margin: 0 10px;
}

.captcha-image {
  position: absolute;
  right: 2px;
  cursor: pointer;
  height: 36px;
  border-radius: 4px;
}
</style>